<?php

namespace App\Http\Controllers;

use App\Http\Service\QuestionsService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class QuestionsController extends  Controller{

    public function index(Request $request){
        $int_type = $request->type?$request->type: 0;
        $arr_type = QuestionsService::getTypes();
        $obj_questions = QuestionsService::getQuestionListPageInit($int_type);

        return view('questions.index',[
            'types' =>$arr_type,
            'currentType' =>$int_type,
            'quesions' => $obj_questions
        ]);
    }

    public function  create(Request $request){
        $arr_type = QuestionsService::getTypes();
        return view('questions.create',[
            'types' =>$arr_type,
        ]);
    }

    public function doCreate(Request $request){
        $this->__validate($request);
        $arr_info = $request->info;
        $arr_info['exam_time'] = strtotime($arr_info['exam_time']);
        if(QuestionsService::createOneQuestion($arr_info)){
            return redirect('/quetions/index');
        }
        return redirect()->back()->withErrors('保存失败！');
    }

    public function delete(Request $request){
        $int_id = $request->id;
        if (QuestionsService::deleteQuestions([$int_id])){
            return $this->output(1,'操作成功！');
        }else{
            return $this->output(0,'操作失败！');
        }
    }

    public function edit(Request $request){
        $int_questionId = $request->id;

        $arr_type = QuestionsService::getTypes();
        $obj_info = QuestionsService::getOneQuestionInfo($int_questionId);
        return view('questions.edit',[
            'types' =>$arr_type,
            'info' => $obj_info
        ]);
    }

    public function doEdit(Request $request){
        $this->__validate($request);
        $arr_info = $request->info;
        if(QuestionsService::editQuestion($arr_info)){
            return redirect('/quetions/index');
        }
        return redirect()->back()->withErrors('保存失败！');
    }

    private function __validate(Request $request){
        return $this->validate($request,[
            'info.title'=>'required',
            /*'show-time-temp'=>'required',
            'info.type'=>'required|integer',
            'info.source'=>'required|integer',
            'info.sort'=>'required|integer',*/
        ],[
            'required'=>':attribute不能为空',
            'integer'=>':attrbute必须为整数'
        ],[
            'info.title'=>'名称',
            /*'info.type'=>'公告类型',
            'info.source'=>'公告来源',
            'info.sort'=>'排序',
            'show-time-temp'=>'发布时间',*/
        ]);
    }

}